import json
import os
import sys
from datetime import datetime

import mysql.connector
import requests
from mysql.connector import Error


def load_config(config_path):
    """Load configuration from JSON file"""
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Configuration file {config_path} not found!")
        sys.exit(1)
    except json.JSONDecodeError:
        print(f"Invalid JSON in configuration file {config_path}!")
        sys.exit(1)


def get_gitlab_users(base_url, token):
    """Fetch users from GitLab API (single page since <100 users)"""
    headers = {"PRIVATE-TOKEN": token}
    users_url = f"{base_url}/users?per_page=100&page=1"

    print("Fetching users...")
    response = requests.get(users_url, headers=headers)

    if response.status_code != 200:
        print(f"Failed to fetch users: {response.status_code}")
        print(response.text)
        return []

    users = response.json()
    print(f"Fetched {len(users)} users.")
    return users


def connect_to_db():
    """Connect to MySQL database"""
    try:
        connection = mysql.connector.connect(
            host="localhost",
            port=3307,
            database="gitlog",
            user="gitlog_admin",
            password="gitlog_admin",
        )
        if connection.is_connected():
            print("Database connection successful!")
            return connection
    except Error as e:
        print(f"Database connection failed: {e}")
        return None


def import_users_to_db(users, dry_run=False):
    """Import users to account table or print in dry-run"""
    if dry_run:
        print("Dry-run mode: Printing user data without inserting.")
        for user in users:
            user_id = int(user.get("id", 0)) + 20000
            git_instance = "chengdu"
            username = user.get("username")
            print(
                f"Would insert: ID={user_id}, Git Instance={git_instance}, Username={username}, Name={user.get('name')}, Email={user.get('email')}, State={user.get('state')}"
            )
        print(f"Would import {len(users)} users.")
        return

    connection = connect_to_db()
    if not connection:
        return

    cursor = connection.cursor()

    insert_query = """
    INSERT INTO account 
    (id, git_instance, engineer_id, username, acct_fullname, email, state, created_at, last_activity_on, updated_at) 
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    ON DUPLICATE KEY UPDATE
    username = VALUES(username),
    acct_fullname = VALUES(acct_fullname),
    email = VALUES(email),
    state = VALUES(state),
    created_at = VALUES(created_at),
    last_activity_on = VALUES(last_activity_on),
    updated_at = VALUES(updated_at)
    """

    inserted_count = 0
    for user in users:
        try:
            user_id = int(user.get("id", 0)) + 20000
            git_instance = "chengdu"
            engineer_id = None  # As per table, allow NULL
            username = user.get("username")
            acct_fullname = user.get("name")
            email = user.get("email")
            state = user.get("state")

            # Parse dates
            created_at = None
            if user.get("created_at"):
                try:
                    created_at = datetime.strptime(
                        user["created_at"], "%Y-%m-%dT%H:%M:%S.%fZ"
                    )
                except ValueError:
                    print(f"Invalid created_at format for user {username}")

            last_activity_on = None
            if user.get("last_activity_on"):
                try:
                    last_activity_on = datetime.strptime(
                        user["last_activity_on"], "%Y-%m-%d"
                    ).date()
                except ValueError:
                    print(f"Invalid last_activity_on format for user {username}")

            updated_at = datetime.now()

            cursor.execute(
                insert_query,
                (
                    user_id,
                    git_instance,
                    engineer_id,
                    username,
                    acct_fullname,
                    email,
                    state,
                    created_at,
                    last_activity_on,
                    updated_at,
                ),
            )
            inserted_count += 1
        except Error as e:
            print(f"Error inserting user {user.get('username')}: {e}")

    connection.commit()
    cursor.close()
    connection.close()

    print(f"Imported {inserted_count} users successfully.")


def main():
    # Get config path (relative to this script in data/)
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(script_dir, "..", "gitlab-api-test", "config.json")

    config = load_config(config_path)
    env_name = "jwzh"  # Fixed to local as per request
    if env_name not in config:
        print(f"Environment '{env_name}' not found!")
        sys.exit(1)

    env_config = config[env_name]
    base_url = env_config["url"]
    token = env_config["token"]

    dry_run = "--dry-run" in sys.argv
    users = get_gitlab_users(base_url, token)
    if users:
        import_users_to_db(users, dry_run)


if __name__ == "__main__":
    main()
